<template>
  <!-- 视频容器 -->
  <div class="relative bg-white h-full w-full ">
    <div id="ttsa" class="ttsa relative z-0 overflow-hidden w-full h-full" @click.capture="handShowController"></div>
    <img v-show="ttsa.reconnecStatus" :src="reconnectBg" alt=""
      class="absolute top-0 z-10 left-0 w-screen h-screen object-cover">
    <reconnect v-show="ttsa.reconnecStatus" />
    <router-view />
  </div>
</template>

<script lang="ts" setup name="App">
import { useTtsaStore } from "@/store/ttsa"
import { useConfigStore } from '@/store/config'
import { useUIStore } from '@/store/ui';
import { useTrack } from "@/hooks"
import { isWechat, checkWebpFeature } from "@/utils/client";
import useWxShare from '@/hooks/useWxShare'
import { equ } from "@env";

const ttsa = useTtsaStore();

const config = useConfigStore()

const ui = useUIStore()

const reconnectBg = computed(() => {
  return new URL(equ === 'pc' ? './assets/images/pc/reconnect-bg.jpg' : '@/assets/white-theme/images/reconnect-bg.jpg', import.meta.url).href
})

if (isWechat()) {
  // 针对ios分享 需记录首次访问链接
  localStorage.setItem('firstUrl', location.href)
  Promise.all([config.getLoadingConfig(), config.getShareConfig()]).then(() => {
    useWxShare().handShare()
  })
} else {
  config.getLoadingConfig()
}

// 判断浏览器是否支持webp
checkWebpFeature('lossy', (feature, isSupported) => {
  if (isSupported) ui.isSupportWebp = true
})

const handShowController = (event) => {
  if (event.target?.srcObject?.id === 'janus') ttsa.showController()
}

onMounted(async () => {
  ttsa.init()

  const track = useTrack()

  provide('setTrack', track.setTrack)

  const { identify, onLoad } = track
  // 初始化埋点信息
  onLoad()
  // 个人标识
  identify()

  window.addEventListener('online', e => {
    console.log('网路连上了');
    window._online = true
    if (ttsa.hasController && !ttsa.reconnecting) ttsa.reconnect()
  })
  window.addEventListener('offline', e => {
    console.log('网路断掉了');
    window._online = false
    if (ttsa.hasController) ttsa.reconnecStatus = 'start'
  })

  if (equ !== 'pc') {
    document.addEventListener('visibilitychange', () => {
      if (!ttsa.hasController) return
      if (document.visibilityState === 'hidden') {
        ttsa.pause()
      } else {
        ttsa.goon()
      }
    })
  }

})
</script>
